/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.vote;

import app.models.member.Member;
import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.kit.Tuple;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import org.joda.time.DateTime;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * The table ol_vote mapping model.
 * </p>
 */
@TableBind(tableName = "ol_vote")
public class Vote extends Model<Vote> {

    /**
     * The public dao.
     */
    public static final  Vote   dao                  = new Vote();
    private static final long   serialVersionUID     = 1L;
    private static final String INSERT_VOTE_JOIN     = "insert into ol_vote_join (join_user, vote, join_time, choose) values('%s', '%s', '%s', '%s')";
    private static final String UPDATE_STAT          = "UPDATE ol_vote_stat SET choose_times = choose_times + 1 WHERE vote =%s AND choose_item = '%s'";
    private static final String INSERT_VOTE_SET_JOIN = "insert into ol_vote_set_join (member, vote_set, choose_item, join_time) values('%s', '%s', '%s', '%s')";

    public List<Vote> list() {
        return find(SqlKit.sql("vote.list"));
    }

    public Page<Vote> datatable(DatatablesCriterias criterias) {
        int pageSize = criterias.getDisplaySize();
        int start = criterias.getDisplayStart() / pageSize + 1;
        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();

        String where = SqlKit.sql("vote.columns-where");

        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            final String byColumns = orderBy.toString();
            if (!Strings.isNullOrEmpty(byColumns)) {
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY category DESC, sequence";
        }

        return paginate(start, pageSize, SqlKit.sql("vote.columns-select"), where);
    }

    /**
     * 前台问题列表
     *
     * @return
     */
    public List<Vote> frontList() {
        return find(SqlKit.sql("vote.columns-select") + SqlKit.sql("vote.columns-where") + SqlKit.sql("vote.append-where-state"));
    }

    public List<Vote> findByCategoryId(int id) {
        return find(SqlKit.sql("vote.findByCategoryId"), id);
    }

    public List<Vote> findBySet(int setId) {

        return find(SqlKit.sql("vote.findBySet"), setId);
    }

    public void memberVote(final Member member, final int vote_set, final Date current,
                           final List<Tuple<String, String>> answers,
                           final String choose_vals) {
        final long memberId = member.getNumber(AppFunc.TABLE_PK_COLUMN).longValue();
        String dateStr = new DateTime(current).toString(AppFunc.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        List<String> allSql = Lists.newArrayList();
        for (Tuple<String, String> answer : answers) {
            final String choose_index = answer.getY();
            final String vote = answer.getX();
            allSql.add(String.format(INSERT_VOTE_JOIN, memberId, vote, dateStr, choose_index));
            allSql.add(String.format(UPDATE_STAT, vote, choose_index));
        }
        allSql.add(String.format(INSERT_VOTE_SET_JOIN, memberId, vote_set, choose_vals, dateStr));
        Db.batch(allSql, 30);
    }
}